import React, { FC } from 'react'
import { Menu } from 'antd'
import SubMenu from 'antd/lib/menu/SubMenu'
import { Link, useLocation } from 'react-router-dom'
import { IRoute, MenuInfo } from '@/interface/router'
import Icon from '@/components/Icon'
import { useStore } from '@/store'
import { observer } from 'mobx-react'
import setRouter from '@/router'

const SiderMenu: FC = () => {
  const { appStore, userStore } = useStore()
  const { menu } = userStore

  let openMenu: Array<string> = []
  let openKey: Array<string> = []

  const getMenuTree = (routers: IRoute[]) => {
    return routers.reduce((pre: any, item: any) => {
      if (!item.children) {
        pre.push(
          <Menu.Item key={item.path} icon={<Icon type={item.icon} />}>
            <Link to={item.path}>
              <span>{item.title}</span>
            </Link>
          </Menu.Item>,
        )
      } else {
        !item.hidden && pre.push(
          <SubMenu key={item.name} title={item.title} icon={<Icon type={item.icon} />}>
            {getMenuTree(item.children)}
          </SubMenu>,
        )
      }

      return pre
    }, [])
  }
  const asyncRoutes = setRouter(menu)
  const menuTree = getMenuTree(asyncRoutes)

  const selectBreadcrumb = (currentKey: string, pathname: string) => {
    const currentMenu: any = []

    asyncRoutes.forEach((item) => {
      if (item.path === currentKey) {
        currentMenu.push({ title: item.title, path: pathname })
      }
      if (item.children) {
        item.children.forEach((sItem) => {
          if (sItem.path === pathname) {
            currentMenu.push({ title: sItem.title, path: pathname })
          }
        })
      }
    })
    return currentMenu
  }

  // 刷新页面，处理默认选中
  // const handleDefaultSelect = () => {
  //   const menuConfigKeys: any = []
  //   router.forEach((item) => {
  //     menuConfigKeys.push(item.path)
  //   })

  //   const { pathname } = window.location
  //   const currentKey = `/${pathname.split('/')[1]}`
  //   const currentMenu = selectBreadcrumb(currentKey, pathname)

  //   if (menuConfigKeys.indexOf(currentKey) !== -1) {
  //     openKey = [pathname]
  //     openMenu = [pathname.split('/')[1]]
  //     appStore.setCurrentMenuList(currentMenu)
  //   }
  // }

  const handleMenuClick = (item: MenuInfo) => {
    const currentKey = `/${item.key.split('/')[1]}`
    const pathname = item.key
    const currentMenu = selectBreadcrumb(currentKey, pathname)
    appStore.setCurrentMenuList(currentMenu)
    openMenu = [item.key.split('/')[1]]
  }

  const Init = () => {
    const location = useLocation()
    const { pathname } = location
    openKey = [pathname]
    openMenu = [pathname.split('/')[1]]
  }

  Init()

  return (
    <div className="app-sider-menu">
      <Menu mode="inline" theme="dark" selectedKeys={openKey} defaultOpenKeys={openMenu} onClick={handleMenuClick} className="app-menu-inner">
        {menuTree}
      </Menu>
    </div>
  )
}

export default observer(SiderMenu)
